package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.service.OrderService;
import com.itheima.health.vo.MemberOrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 提交体检信息
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Order addOrder(Order order) {
        //查询是否已经预约过，如果已经预约过的话就不能当天就不能再继续预约了
        //查询ordersetting表 是否当天有预约记录了
        String date = new SimpleDateFormat("yyyy-MM-dd").format(order.getOrderDate());
        OrderSetting orderSetting = orderSettingDao.selectByDate(date);
        if (null == orderSetting) {
            //如果不存在-不能预约
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        }
        //如果预约人数满了，就不允许预约
        if (orderSetting.getReservations() == orderSetting.getNumber()) {
            throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
        }
        //查询是否重复预约
        long count = orderDao.selectOrder(order.getMemberId(), date, order.getSetmealId());
        System.out.println("count = " + count);
        //如果预约过抛异常
        if (count > 0) {
            throw new BusinessRuntimeException(MessageConst.HAS_ORDERED);
        }
        //如果没有预约过，就执行SQL语句  新增预约
        order.setFormatOrderDate(date);
        //插入数据
        orderDao.insert(order);

        //修改已预约数
        orderSettingDao.updateReservationsById(orderSetting.getId(), orderSetting.getReservations() + 1);

        return orderDao.selectById(order.getId());
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public Result selectById(Integer id) {
        MemberOrderVo memberOrderVo = orderDao.selectMemberOrderById(id);
        return new Result(true, MessageConst.QUERY_ORDER_SUCCESS, memberOrderVo);
    }
}













